// package-store/pages/store-open/index.js
import { UserInfoUpdateMixins } from '../../../behaviors/page';
import { TARGET_TYPE } from '../../../constants/common';
import { TAB_BAR_PAGE } from '../../../constants/route';
import { reLaunchTo, tipToast, showLoading, hideLoading, tipSuccess } from '../../../common/env';
import { setMangeTargetId } from '../../../biztools/wex';
import { openStore } from '../../../api/sto';

Page({
    mixins: [UserInfoUpdateMixins],
    data: {
        storeInfo: {},
    },
    onLoad(options) {
        const { brandId, distributorId } = options;
        const { pic, nickName } = this.data.userInfo;
        this.setData({
            'storeInfo.pic': pic,
            'storeInfo.name': `${nickName ? nickName + '的小店' : ''}`,
            'storeInfo.brandId': brandId,
            'storeInfo.distributorId': distributorId,
        });
    },
    handleChange(e) {
        const { type } = e.currentTarget.dataset;
        const { storeInfo } = this.data;
        const value = type === 'pic' ? e.detail : e.detail.value;
        storeInfo[type] = value;
        this.setData({ storeInfo });
    },
    async handleCreate() {
        const { storeInfo } = this.data;
        const { pic, name } = storeInfo;
        if (!pic) {
            tipToast('请上传店铺LOGO');
            return;
        }
        if (!name) {
            tipToast('请输入店铺名称');
            return;
        }
        showLoading('保存中...');
        const flag = await openStore(storeInfo);
        if (flag) {
            hideLoading();
            tipSuccess('创建成功');
            setMangeTargetId(TARGET_TYPE.store, flag.storeId);
            reLaunchTo(TAB_BAR_PAGE['star']);
        }
    },
})
